import React from 'react';
import './hardwareConfigDetail.scss';
import AreaData from '../../../component/areaData/areaData.js'; //地址库
import utils from '../../../utils/utils';
import cookie from 'react-cookies';
import BMap from 'BMap';
import moment from 'moment';
import BreadcrumbNav from '../../../component/breadcrumb/breadcrumb.js';
import { Modal, Tabs, Row, Col, Select, DatePicker, Table, Button, Input, Card, message } from 'antd';
import { EditOutlined, DeleteOutlined ,SettingOutlined,LoadingOutlined, PlusOutlined ,UploadOutlined} from '@ant-design/icons';
import { getEquipmentList, getProjectEquipment, getProjectEqDetailLog, addEquipment, updEquipment, delEquipment } from '../../../api/hardwareCenter'
import { brandList } from '../../../api/deviceLibrary'
import Pagination from '../../../component/Pagination/Pagination.js';

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { Option } = Select;
const { Column } = Table;
const { TextArea } = Input;

class hardwareConfigDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            project_id: this.props.location.search.split('?')[1],
            activeKey: '1',
            RangePickerVal:[],
            changeType: undefined,
            keyWord:'',
            proName:'',
            List:[],
            EquipmentList:[],
            LogList:[],
            visibleInfo:false,
            amendInfo:false,
            pageSize: 10,
            total_count: 0,
            current: 1,

            brandNameList:[],

            cate_name: undefined,
            lane_num: undefined,
            lane_type: undefined,
            inlet_outlet_type:undefined, 
            ip: '', 
            port: '', 
            config_address: '', 
            brand_name: undefined,
            activeItem:{
                project_name:'--',
            },
            activeLaneNum: []
          
          
        }
    }

    componentDidMount() {
        console.log(this.props)
        console.log('项目ID', this.props.location.search)
        const activeKey = sessionStorage.getItem('activeType')
        const activeItem = JSON.parse(sessionStorage.getItem('activeItem'))
        let activeLaneNum = []
        for (let i = 0; i < activeItem.lane_count; i++) {
            activeLaneNum.push(String(i+1))
        }
        this.setState({
            activeKey, activeLaneNum, activeItem
        }, () => {
            if (activeKey === '1') {
                this.getList()
            } else if(activeKey === '2') {
                this.getEquipment()
            } else {
                this.getEqDetailLog()
            }
        })
    }
    componentDidUpdate(prevProps){
        const { activeKey } = this.state;
        const { search } = this.props.location;
        const activeItem = JSON.parse(sessionStorage.getItem('activeItem'))
        console.log('项目ID--', prevProps.location.search, search)
        if (prevProps.location.search !== search) {
            let activeLaneNum = []
            for (let i = 0; i < activeItem.lane_count; i++) {
                activeLaneNum.push(String(i + 1))
            }
            this.setState({
                project_id: search.split('?')[1],
                activeItem,
                activeLaneNum
            }, () => {
                if (activeKey === '1') {
                    this.getList()
                } else if (activeKey === '2') {
                    this.getEquipment()
                } else {
                    this.getEqDetailLog()
                }
            })
        } 
    }

    callback = (e) => {
        this.setState({
            activeKey:e
        },()=>{
            if (e === '1') {
                this.getList()
            } else if (e === '2') {
                this.getEquipment()
            } else {
                this.getEqDetailLog()
            }
        })
    }
   
    //时间周期筛选
    onChangeDate = (val, valString) => {
        console.log(val, valString)
        const start_time = valString[0];
        const end_time = valString[1];
        this.setState({ RangePickerVal: val, start_time, end_time })
    }

    //获取硬件配置
    getList = () => {
        const { project_id } = this.state;
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
            'project_id': project_id,
        }
        console.log(post_data)
        getEquipmentList(post_data).then(res => {
            console.log(res)
            this.setState({
                List: res.data
            })
        })
    }
    //获取机房设备
    getEquipment = () => {
        const { project_id } = this.state;
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
            'project_id': project_id,
        }
        console.log(post_data)
        getProjectEquipment(post_data).then(res => {
            console.log(res)
            this.setState({
                EquipmentList: res.data
            })
        })
    }
    //获取日志
    getEqDetailLog = () => {
        const { project_id, start_time, end_time, changeType, current } = this.state;
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
            'project_id': project_id,
            'start_time': start_time,
            'end_time': end_time,
            'type': changeType,
            'page': current
        }
        console.log(post_data)
        getProjectEqDetailLog(post_data).then(res => {
            console.log(res)
            this.setState({
                LogList: res.data
            })
        })
    }
    //获取设备品牌列表
    getBrandList = id => {
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
            'id': id,
        }
        console.log(post_data)
        brandList(post_data).then(res => {
            console.log(res)
            this.setState({
                brandNameList: res.data.brand_list
            })
        })
    }

    // 编辑维护操作
    edited = (id, row) => {
        console.log('编辑',id,row)
        this.setState({
            detail_id:id,
            cate_id: row.cate_id,
            cate_name: row.cate_name,
            lane_num: row.lane_num,
            lane_type: row.lane_type,
            inlet_outlet_type: row.inlet_outlet_type,
            ip: row.ip,
            port: row.port,
            config_address: row.config_address,
            brand_name: row.brand_name,
            visibleInfo: true,
            amendInfo: true
        })
    }

    // 删除操作
    delete = id => {
        console.log('删除',id)
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
            'detail_id': id,
        }
        console.log(post_data)
        delEquipment(post_data).then(res => {
            console.log(res)
            message.success(res.message, 1);
            this.getList();
        })
    }

    // 规格设置
    SpeSet = (id,type) => {
        console.log('规格设置',id)
        this.setState({
            cate_id:id
        })
    }
    //新增配置
    add = row =>{
        if (row.use_count == row.total_count){
            message.error('新增配置数量已是最大数量！', 2);
            return;
        }
        if (row.cate_id === 8) {
            this.getBrandList(row.cate_id);
        }
        this.setState({
            cate_id: row.cate_id,
            cate_name: row.cate_name,
            visibleInfo:true
        })
        console.log(this.state.cate_name)
    }
    //返回修改
    toCancel = () => {
        this.setState({
            cate_id:undefined,
            cate_name: undefined,
            lane_num: undefined,
            lane_type: undefined,
            inlet_outlet_type: undefined,
            ip: '',
            port: '',
            config_address: '',
            brand_name: undefined,
            visibleInfo: false,
            amendInfo: false
        })
    }
    //确认编辑
    toEdit = () => {
        const { project_id, cate_id, cate_name, lane_num, lane_type, inlet_outlet_type, ip, port, config_address, brand_name, amendInfo, detail_id } = this.state;
        if (!cate_id) { message.error('请选择设备种类！', 2); return }
        if (cate_id !== 8 &&!lane_num) { message.error('请选择所属车道！', 2); return }
        if (cate_id !== 8 && cate_id !== 5&&!lane_type) { message.error('请选择车道性质！', 2); return }
        if (cate_id !== 8 &&!inlet_outlet_type) { message.error('请选择出入口！', 2); return }
        if (cate_id === 8 && !lane_num) { message.error('请选择安装位置！', 2); return }
        if (cate_id === 8 && !brand_name) { message.error('请选择打印机品牌！', 2); return }
        if (!ip) { message.error('请输入ip！', 2); return }
        if (!port) { message.error('请输入端口号！', 2); return }
        
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
            'project_id': project_id,
            'cate_id': cate_id,
            'cate_name': cate_name,
            'lane_num': lane_num,
            'lane_type': lane_type,
            'inlet_outlet_type': inlet_outlet_type === 0 ? undefined : inlet_outlet_type,
            'ip': ip,
            'port': port,
            'config_address': config_address || undefined,
            'brand_name': brand_name || undefined,
            'detail_id': amendInfo ? detail_id : undefined
        }
        console.log(post_data)
        const addEquipmentRequest= amendInfo ? updEquipment : addEquipment;
        addEquipmentRequest(post_data).then(res => {
            console.log(res)
            message.success(res.message, 1);
            this.getList();
            this.toCancel();
        })
    }

    //分页获取数据
    setPaginationPage = pageNumber => {
        console.log('Page: ', pageNumber);
        const { pageType } = this.state;
        console.log(pageType)
        this.setState({
            current: pageNumber
        }, () => {
            this.getEqDetailLog()
        })
    }
    //变更类型
    onChangeType = e =>{
        console.log(e)
        this.setState({
            changeType:e
        })
    }

    //设备种类
    onChangeCateName = (e,val) => {
        console.log(e, val)
        if(e === 8){
            this.getBrandList(e);
        }
        this.setState({
            cate_id: e,
            cate_name: val.children
        })
    }
    
    //所属车道
    onChangeLaneNum = e => {
        console.log(e)
        this.setState({
            lane_num: e
        })
    }   
    //打印机品牌
    onChangeBrandName = e => {
        console.log(e)
        this.setState({
            brand_name: e
        })
    }
    //车道性质
    onChangeLaneType = e => {
        console.log(e)
        this.setState({
            lane_type: e
        })
    }
    //出入口
    onChangeInletOutletType = e => {
        console.log(e)
        this.setState({
            inlet_outlet_type: e
        })
    }
    //IP
    onChangeIp = e => {
        this.setState({
            ip: e.currentTarget.value
        })
    }
    //端口号
    onChangePort = e => {
        this.setState({
            port: e.currentTarget.value
        })
    }
    //配置地址
    onChangeAddress = e => {
        this.setState({
            config_address: e.currentTarget.value
        })
    }


    //查询
    search = () =>{
        this.setState({
            current: 1
        },()=>{
            this.getEqDetailLog()
        })
    }
    //清空按钮
    clear = () => {
        console.log('--')
        this.setState({
            RangePickerVal: [],
            start_time: '',
            end_time: '',
            changeType: undefined,
            current: 1
        }, () => {
            this.getEqDetailLog()
        })
    }

    render() {
        const { 
            activeKey, RangePickerVal, changeType, List, EquipmentList, 
            LogList, visibleInfo, cate_id, pageSize, total_count, current, activeLaneNum, activeItem,
            cate_name, lane_num, lane_type, inlet_outlet_type, ip, port, config_address, brand_name, brandNameList
        } = this.state;
        return (
            <div className="detailCon">
                <div className="detailbox">
                    <Tabs activeKey={activeKey} onChange={this.callback}>
                        <TabPane tab={<span className="tabTit">车道设备</span>} key="1">
                            <Row>
                                <Col span={24}>
                                    <div className="topName">
                                        <span className="name">{activeItem.project_name}</span>
                                        <span className="name1">{`${activeItem.lane_in_count}进${activeItem.lane_out_count}出`}</span>
                                        <span className="name1">{(() => {
                                            if (activeItem.project_phase === 1) {
                                                return ' - 厂区建设阶段'
                                            } else if (activeItem.project_phase === 2) {
                                                return ' - 道闸施工阶段'
                                            } else if (activeItem.project_phase === 3) {
                                                return ' - 软件调试阶段'
                                            } else if (activeItem.project_phase === 4) {
                                                return ' - 维保期内'
                                            } else {
                                                return ' - 服务到期'
                                            }
                                        })()}</span>
                                    </div>
                                </Col>
                                <Col span={24}>
                                    {List.map((el,index)=>(
                                        <Card title={el.cate_name + `（${el.use_count}/${el.total_count}）`} size="small" extra={<Button style={{ color: '#2F3CF2' }} type="text" className="but_text" onClick={this.add.bind(this, el)}> + 新增配置</Button>} style={{ width: '100%' }} key={index}>
                                            <Table dataSource={el.eq_info} rowKey={record => record.id} scroll={{ x: '100%' }} pagination={false} locale={{ emptyText: '暂无数据' }}>
                                                <Column className="thbg" title={`${el.cate_name}编号 - 车道${el.cate_id === 1 || el.cate_id === 2 ? " - 出入口" : ''}`} render={item => 
                                                    `${item.hardware_num}-0${item.lane_num}号车道${el.cate_id === 1 || el.cate_id === 2 ? '-'+(item.lane_type == 1 ? '入口' : '出口') : ''}`
                                                    } width='250px' key='1' />
                                                {el.cate_id === 8 ? <Column className="thbg" title="打印机类型-品牌" render={record => '小票打印机-' + record.brand_name} width='200px' key='3' /> : ''}
                                                <Column className="thbg" title="IP/端口号" render={record => record.ip + ':' + record.port } width='200px' key='2' />
                                                {/* {el.cate_id === 1 ? <Column className="thbg" title="停车场ID" dataIndex="park_id" width='200px' key='3' /> : ''} */}
                                                <Column className="thbg" title="配置地址" width='250px' key='4'
                                                    render={record => {
                                                        return <span>
                                                            <span className="link" onClick={this.SpeSet.bind(this, record.id, el.cate_id)}>{record.config_address?record.config_address:'-'}<span className="icon"></span></span>
                                                        </span>
                                                    }}
                                                />
                                                <Column className="thbg" title="操作" width='140px' key='5' fixed='right'
                                                    render={record => {
                                                        return <span>
                                                            {el.cate_id === 8 ? <span className="link" >测试打印</span> : ''}
                                                            <span className="link" onClick={this.edited.bind(this, record.id, record)}>维护</span>
                                                            <span className="link" onClick={this.delete.bind(this, record.id)}>删除</span>
                                                        </span>
                                                    }}
                                                />
                                            </Table>
                                        </Card>
                                    ))}
                                </Col> 
                            </Row>
                        </TabPane>
                        <TabPane tab="机房设备" key="2">
                            <Row>
                                <Col span={24}>
                                    <div className="topName">
                                        <span className="name">{activeItem.project_name}</span>
                                        <span className="name1">{`${activeItem.lane_in_count}进${activeItem.lane_out_count}出`}</span>
                                        <span className="name1">{(()=>{
                                            if (activeItem.project_phase === 1){
                                                return ' - 厂区建设阶段'
                                            } else if (activeItem.project_phase === 2) {
                                                return ' - 道闸施工阶段'
                                            } else if (activeItem.project_phase === 3) {
                                                return ' - 软件调试阶段'
                                            } else if (activeItem.project_phase === 4) {
                                                return ' - 维保期内'
                                            } else {
                                                return ' - 服务到期'
                                            }
                                        })()}</span>
                                    </div>
                                </Col>
                                <Col span={24}>
                                    <Card title="机房设备" size="small" style={{ width: '100%' }}>
                                        <Table dataSource={EquipmentList} rowKey={record => record.eq_id} scroll={{ x: '100%' }} pagination={false} locale={{ emptyText: '暂无数据' }}>
                                            <Column className="thbg" title="设备种类" dataIndex="eq_name" width='120px' key='1' />
                                            <Column className="thbg" title="设备型号" dataIndex="eq_model" width='200px' key='2' />
                                            <Column className="thbg" title="品牌" dataIndex="eq_brand_name" width='200px' key='3' />
                                            <Column className="thbg" title="设备规格" dataIndex="spec_value" width='300px' key='4' />
                                        </Table>
                                    </Card>
                                </Col>
                            </Row>
                        </TabPane>
                        <TabPane tab="配置记录" key="3">
                            <Row>
                                <Col  span={6}>
                                    <span className="tit">变更类型：</span>
                                    <Select value={changeType} size="small" placeholder="全部" onChange={this.onChangeType}  allowClear>
                                        <Option value={1}>设备新增</Option>
                                        <Option value={2}>设备维护</Option>
                                        <Option value={3}>设备删除</Option>
                                        <Option value={4}>工单新增</Option>
                                    </Select>
                                </Col>
                                <Col  span={12}>
                                    <span className="tit">变更时间：</span>
                                    <RangePicker onChange={this.onChangeDate} placeholder={['开始时间', '结束时间']} value={RangePickerVal} />
                                </Col>
                                <Col  className="bottom" span={6}>
                                    <Button className="search" onClick={this.search}>查询</Button>
                                    <Button className="toClear" onClick={this.clear}>重置</Button>
                                </Col>
                            </Row>
                            <Row>
                                
                                
                            </Row>
                            <Row className="table">
                                <Col span={24}>
                                    <Table dataSource={LogList} rowKey={record => record.log_id} scroll={{ x: '100%' }} pagination={false} locale={{ emptyText: '暂无数据' }}>
                                        <Column title="变更类型" dataIndex="type" width='150px' key='1' />
                                        <Column title="设备类型" dataIndex="cate_name" width='150px' key='2' />
                                        <Column title="设备编号" render={item => item.hardware_num||'--'} width='150px' key='3' />
                                        <Column title="变更前" render={item => item.before_desc || '--'} width='150px' key='4' />
                                        <Column title="变更后" render={item => item.after_desc || '--'} width='150px' key='5' />
                                        <Column title="变更时间" dataIndex="opt_time" width='150px' key='6' />
                                        <Column title="操作用户" dataIndex="opt_user" width='100px' key='7' />
                                        <Column title="" width="0px" key="12" fixed="right" />
                                    </Table>
                        
                                </Col>
                            </Row>
                            <Pagination pageSize={pageSize} total={total_count} current={current} getChangeData={this.setPaginationPage.bind(this)} />
                        </TabPane>

                    </Tabs>
                   
                </div>
                <Modal
                    visible={visibleInfo}
                    onOk={this.toEdit.bind(this)}
                    onCancel={this.toCancel.bind(this)}
                    wrapClassName="recordModal"
                    width="620"
                    centered
                    okText="确认保存"
                    cancelText="返回修改"
                    maskClosable={false}
                >
                    <span>
                        <div className="title">设备信息配置</div>
                        <div className="li">
                            <span className="tit">设备种类：</span>
                            <Select value={cate_id} onChange={(e,el) => this.onChangeCateName(e,el)} size="small" placeholder="请选择设备种类" allowClear>
                                <Option value={1}>道闸</Option>
                                <Option value={2}>抓拍机</Option>
                                <Option value={5}>串口服务器</Option>
                                <Option value={8}>打印机</Option>
                            </Select>
                        </div>   
                        {cate_id === 1 || cate_id === 2 ? <div className="li">
                            <span className="tit">所属车道：</span>
                            <Select value={lane_num} onChange={this.onChangeLaneNum} size="small" placeholder="请选择车道编号" allowClear>
                                {activeLaneNum.map(row => (
                                    <Option value={row} key={row}>0{row}号车道</Option>
                                ))}
                            </Select>
                        </div> : ''}
                        {cate_id === 8 ? <div className="li">
                            <div className="li_cell">
                                <span className="tit">安装位置：</span>
                                <Select value={lane_num} onChange={this.onChangeLaneNum} size="small" placeholder="请选择打印机安装位置" allowClear>
                                    {activeLaneNum.map(row => (
                                        <Option value={row} key={row}>0{row}号车道</Option>
                                    ))}
                                </Select>
                            </div>
                            <div className="li_cell">
                                <span className="tit">打印机品牌：</span>
                                <Select value={brand_name} onChange={this.onChangeBrandName} size="small" placeholder="请选择打印机品牌" allowClear>
                                    {brandNameList.map((row,index)=>(
                                        <Option value={row.bd_id} key={index}>{row.bd_name}</Option>
                                    )) }
                                </Select>
                            </div>
                        </div> : ''}
                        {cate_id === 1 || cate_id === 2 ? <div className="li">
                            <div className="li_cell">
                                <span className="tit">车道性质：</span>
                                <Select value={lane_type} onChange={this.onChangeLaneType} size="small" placeholder="请选择车道性质" allowClear>
                                    <Option value={1}>入场车道</Option>
                                    <Option value={2}>出场车道</Option>
                                </Select>
                            </div>
                            <div className="li_cell">
                                <span className="tit">出入口：</span>
                                <Select value={inlet_outlet_type} onChange={this.onChangeInletOutletType} size="small" placeholder="请选择道闸安装位置" allowClear>
                                    <Option value={1}>入口</Option>
                                    <Option value={2}>出口</Option>
                                </Select>
                            </div>
                        </div> : ''}
                        {cate_id === 5 ? <div className="li">
                            <div className="li_cell">
                                <span className="tit">所属车道：</span>
                                <Select value={lane_num} onChange={this.onChangeLaneNum} size="small" placeholder="请选择车道编号" allowClear>
                                    {activeLaneNum.map(row=>(
                                        <Option value={row} key={row}>0{row}号车道</Option>
                                    )) }
                                </Select>
                            </div>
                            <div className="li_cell">
                                <span className="tit">出入口：</span>
                                <Select value={inlet_outlet_type} onChange={this.onChangeInletOutletType} size="small" placeholder="请选择道闸安装位置" allowClear>
                                    <Option value={1}>入口</Option>
                                    <Option value={2}>出口</Option>
                                </Select>
                            </div>
                        </div> : ''}
                        <div className="li">
                            <span className="tit">IP/端口号：</span>
                            <div className="number">
                                <div className="cell">
                                    <Input value={ip} onChange={this.onChangeIp} />
                                    <Input value={port} className="num" placeholder="请输入端口号" onChange={this.onChangePort} />
                                </div>
                                <div className="ts">IP地址分为4段，每段范围为0～255的整数；端口号范围为0～65535的整数</div>
                            </div>
                            
                        </div>
                        {/* {cate_id === 1 || cate_id === 2 ? <div className="li">
                            <span className="tit">停车场ID：</span>
                            <Select value={park_id} onChange={this.onChangeParkId} size="small" placeholder="请选择对应的停车场ID" allowClear>
                                <Option value="1">设备新增</Option>
                            </Select>
                        </div> : ''} */}
                        {cate_id === 8 ? '' : <div className="li">
                            <span className="tit">配置地址：</span>
                            <TextArea placeholder="(选填)" value={config_address} onChange={this.onChangeAddress}/>
                        </div>}
                    </span>
                </Modal>
            </div>
        )
    }
}

export default hardwareConfigDetail;